package com.jd.org.service.impl;

import com.jd.basic.service.impl.BaseServiceImpl;
import com.jd.org.domain.Department;
import com.jd.org.mapper.DepartmentMapper;

import com.jd.org.service.DepartmentService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 小林同学
 * @version 1.0
 * @description: TODO
 * @date 2023/2/18 20:51
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    // 获取上级部门
    @Override
    public List<Department> getParent() {
        // 查询所有的部门
        List<Department> departments = findAll();
        // 创建一个空的集合,负责存储无限极数的部门
        ArrayList<Department> depts = new ArrayList<>();

        Map<Long, Department> departmentMap = departments.stream().collect(Collectors.toMap(Department::getId, item -> item));
        // 首先遍历部门集合
        for (Department department:departments) {
            // 如果 该部门的parentId等于null，则该部门没有上级部门，说明他是父级部门
            if (department.getParentId() == null) {
                // 将父级部门添加进入空集合里
                depts.add(department);
            } else {
                // 寻找子部门
                Department childDepartment = departmentMap.get(department.getParentId());
                if (childDepartment != null) {
                    childDepartment.getChildren().add(department);
                }
                System.out.println(department);
//                // 再次遍历集合里的部门
//                for (Department child: depts) {
//                    // 父级部门的parentId等于子部门的id，说明他们是父子关系
//                    if (child.getId() == department.getParentId()) {
//                        // 将子部门加入到父级部门
//                        child.getChild().add(department);
//                        break;
//                    }
//                }
            }
        }
        return depts;
    }

}
